import React, { Component } from 'react';
import Editor from '@/utils/Editor';
import { Icon, Radio, Select, Button, Table, Row, Col } from 'antd';
import {withPropsAPI} from "gg-editor";
import { FormattedMessage } from 'umi-plugin-react/locale';
import styles from './index.less';
import {connect} from "dva/index";
import {message} from "antd/lib/index";
import savebuttom from '@/assets/account/robotSetup/savebuttom.png';
import addImg from '@/assets/dialog/add1.png';
import add2Img from '@/assets/dialog/add2.png';
import delImg from '@/assets/dialog/del1.png';
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_m18hmgbwet.js', // 在 iconfont.cn 上生成
});

@connect(({ dialogCommon, loading }) => ({
  dialogCommon,
  loading: loading.models.data,
}))
class ActionApi extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      dialogId: props.dialogId,
      nodeId: props.nodeId,
      stage: props.stage,
      stageId: "",
      slots:[],
      apiList:[],
      requestFieldList: [],
      responseFieldList: [],
      currentApi:'',
      mapping : [],
    };
  }

  componentDidMount() {
    this.getInit();
    this.loadActionApis();
  };

  getInit = () =>{
    const { dispatch } = this.props;
    const { nodeId, dialogId, stage } = this.state;
    console.log("nodeId: " + nodeId + ", dialogId :" + dialogId);
    dispatch({
      type: 'dialogCommon/getStage',
      payload: {
        dialogId: dialogId,
        nodeId: nodeId,
        stage: stage,
        field: "api",
      },
      callback:(res)=>{
        console.log("动作-调用API接口返回值 :" + JSON.stringify(res));
        this.setState({
          slots: res.dialogSlots==null?[]:res.dialogSlots,
          stageId: res.dialogStage._id,
          currentApi: res.dialogStage.api==null?"":res.dialogStage.api.apiId,
          mapping: res.dialogStage.api==null?[]:res.dialogStage.api.mapping,
        },() =>{
          this.loadApiFields(this.state.currentApi);
        });
      }
    });
  };

  loadActionApis = () =>{
    const { dispatch } = this.props;
    const { nodeId, dialogId, stage } = this.state;
    console.log("nodeId: " + nodeId + ", dialogId :" + dialogId);
    dispatch({
      type: 'dialogCommon/loadActionApis',
      payload: {
        page: 0,
        limit: 99999,
      },
      callback:(res)=>{
        console.log("动作-API列表返回值 :" + JSON.stringify(res));
        this.setState({
          apiList: res==null?[]:res,
        });
      }
    });
  };

  loadApiFields = (apiId) =>{
    const { dispatch } = this.props;
    dispatch({
      type: 'dialogCommon/loadActionApi',
      payload: {
        apiId: apiId,
      },
      callback:(res)=>{
        console.log("动作-API字段返回值 :" + JSON.stringify(res));
        this.setState({
          requestFieldList: res.requestFields==null?[]:res.requestFields,
          responseFieldList: res.requestFields==null?[]:res.responseFields,
        })
      }
    });
  };

  changeCurrentApi = (val) =>{
    this.setState({
      currentApi: val,
      mapping: [],
    })
    this.loadApiFields(val);
  };

  addField = () =>{
    const { mapping } = this.state;
    mapping.push(
      {
        apiField: "",
        slotId: "",
        fieldType: "N",
      }
    )
    this.setState({
      mapping
    })
  };

  changeSelect = (val, valType, index) =>{
    console.log("val :" + val + ", valType :" + valType + ", index :" + index);
    const { mapping } = this.state;
    console.log("mapping :" + index +" stat : " + JSON.stringify(mapping[index]));
    mapping[index][valType] = val;
    if(valType == "fieldType"){
      mapping[index].apiField = '';
    }
    this.setState({
      mapping: mapping,
    },() =>{
      console.log("mapping :" + index +" end : " + JSON.stringify(this.state.mapping[index]));
    })
  };

  removeMapping = (index) =>{
    const { mapping } = this.state;
    mapping.splice(index, 1);
    this.setState({
      mapping
    })
  }

  save = () =>{
    const obj = {
      _id: this.state.stageId,
      field: "api",
      api:{
        apiId: this.state.currentApi,
        mapping: this.state.mapping,
        setTime: new Date().getTime(),
      }
    }

    console.log("request: " + JSON.stringify(obj));

    if(obj.api.apiId ===''){
      return message.error('请选择API接口后再做保存')
    }else if(obj.api.mapping.length===0){
      // return message.error('请添加词槽和API字段的对应关系')
    }

    const { dispatch } = this.props;
    dispatch({
      type: 'dialogCommon/saveStage',
      payload: obj,
      callback:(res)=>{
        console.log("动作-API接口保存结果 :" + JSON.stringify(res));
        if(res.code === 0){
          message.info("保存成功");
        }else{
          message.info("保存失败");
        }
      }
    });
  };

  render() {
    const columns = [
      {
        title: '词槽',
        width: '30%',
        render: (text,item,index) => {
          return (
            <div>
              <Select style={{ width: '150px' }} value={item.slotId} onChange={(value) => this.changeSelect(value,"slotId",index)}>
                <Select.Option value=''>请选择</Select.Option>
                {
                  this.state.slots.map((slotItem,index) =>
                    <Select.Option value={slotItem.slotId}>{slotItem.slotName}</Select.Option>
                  )
                }
              </Select>
            </div>
          )
        }
      },
      {
        title: 'API字段',
        width: '60%',
        render: (text,item,index) => {
          return (
            <div>
              <Select style={{ width: '150px',marginRight:10}} value={item.fieldType} onChange={(value) => this.changeSelect(value,"fieldType",index)}>
                <Select.Option value='N'>请选择</Select.Option>
                <Select.Option value="request">请求字段</Select.Option>
                <Select.Option value="response">返回字段</Select.Option>
              </Select>
              -
              <Select style={{ width: '150px',marginLeft:10 }} value={item.apiField} onChange={(value) => this.changeSelect(value,"apiField",index)}>
                <Select.Option value="">请选择</Select.Option>
                {
                  item.fieldType == "request"?
                    this.state.requestFieldList.map((field,index) =>
                      <Select.Option value={field.id}>{field.name}</Select.Option>
                    ):
                    this.state.responseFieldList.map((field,index) =>
                      <Select.Option value={field.id}>{field.name}</Select.Option>
                    )
                }
              </Select>
            </div>
          )
        }
      },
      {
        title: '操作',
        width: '10%',
        render: (text, item, index) => {
          return <div className={styles.pb}>
            <div
              // onClick={() => this.removeMapping(index)}
              // style={{ marginLeft: 10, background: '#e8313b' }}
              // className={styles.buttongl}
            >
              {/*<span><Icon size="small" type='delete' style={{ marginRight: 5 }} /></span>*/}
              <img src={delImg} height={30}  style={{cursor:'pointer'}} onClick={() => this.removeMapping(index)}/>
              {/*<span><FormattedMessage id="app.dialog.question.delete" defaultMessage="out" /></span>*/}
            </div>
          </div>
        }
      }
    ]
    return(
      <div>
        <div style={{margin: '15px 0px', paddingLeft:'30px'}} tt="2">
          <span style={{color: '#C8C8C8', fontSize: '18px'}}>API接口</span>
          <Radio.Group value={1} style={{marginLeft:20}}>
            <Radio value={1} style={{ marginLeft: 20 }}>自定义API接口</Radio>
          </Radio.Group>
          <Select style={{ marginLeft: 20,width: 150, boxShadow: "0 0 15px #ccc", border: "none"  }} value={this.state.currentApi} onChange={(value) => this.changeCurrentApi(value)}>
            <Select.Option value='' >请选择接口</Select.Option>
            {
              this.state.apiList.map((item,index) =>
                <Select.Option value={item._id}>{item.name}</Select.Option>
              )
            }
          </Select>
        </div>

        <div>
          <div>
            {/*<Icon style={{transform: 'rotate(90deg)'}} type="minus"/>词槽-字段对应*/}
            <Row>
              <Col xs={24}>
                <div className={styles.title}>
                  <span>词槽-字段对应</span>
                </div>
              </Col>
            </Row>
            <Table
              columns={columns}
              dataSource={this.state.mapping}//数据
              pagination={false}
              style={{marginLeft:'20px', marginTop:'20px'}}
            />
          </div>
          <div style={{marginBottom:'30px'}}>
            <div style={{marginLeft:'20px'}}>
              {/*<span style={{color:'#8EC0F9', cursor: "pointer"}} onClick={this.addField}>+ 添加</span>*/}
              <img src={add2Img} alt="" height={70} style={{marginTop:10,cursor:"pointer"}}  onClick={this.addField} />
            </div>
          </div>
          <div className={styles.flexcen}>
            {/*<Button type="primary" style={{marginLeft:'15px'}} onClick={this.save}>保存</Button>*/}
            <img onClick={this.save} src={savebuttom} />
          </div>
        </div>
      </div>

    )
  }
}

export default withPropsAPI(ActionApi);
